package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {

	public static void main(String[] args) {
		Test1 test1 = new Test1();
		test1.test();
	}

	public void test() {
		User u = new User();

		Thread1 t1 = new Thread1(u);
		Thread2 t2 = new Thread2(u);
		Thread3 t3 = new Thread3(u);
//		ExecutorService pool = Executors.newCachedThreadPool();
//		pool.execute(t1);
//		pool.execute(t2);
//		pool.execute(t3);
		Thread d1 = new Thread(t1 );
		Thread d2 = new Thread(t2);
		d1.start();
		d2.start();
		Thread d3 = new Thread(t3);
		d3.start();
	}

	class User {
		private int num = 0;

		public    void add(int i) {
			num += i;
		}
		
		public  void jian(int i) {
			synchronized (User.class) {
				num = num - i ;
			}
			 
		}
	}

	class Thread1 implements Runnable {
		private User user;

		 

		public Thread1(User user) {
			this.user = user;
		}

		public void run() {

			for (int i = 0; i < 20; i++) {
				try {
					Thread.currentThread().sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				user.add(1);
				System.out.println(Thread.currentThread().getId() +"，user:" + user.num);
			}

		}

	}

	
	class Thread2 implements Runnable {
		private User user;

		public Thread2(User user) {
			this.user = user;
		}

		public void run() {

			for (int i = 0; i < 20; i++) {
				try {
					Thread.currentThread().sleep(150);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				user.jian(1);
				System.out.println(Thread.currentThread().getId() +"，user:" + user.num);
			}

		}

	}
	class Thread3 implements Runnable {
		private User user;

		public Thread3(User user) {
			this.user = user;
		}

		public void run() {

			for (int i = 0; i < 20; i++) {
				try {
					Thread.currentThread().sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				user.jian(1);
				System.out.println(Thread.currentThread().getId() +"，user:" + user.num);
			}

		}

	}
}
